// 收藏集管理云对象
const UniID = require('uni-id-common');
//获取数据库对象
const db = uniCloud.database();
module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
	},

	/**
	 * 获取用户收藏集列表
	 * @returns {object} 收藏集列表
	 */
	async getCollectionList() {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		if (code !== 0 || !uid) {
			return {
				errCode: 401,
				errMsg: '用户未登录'
			}
		}
		const userId = uid
		try {
			const db = uniCloud.database();
			const collectionResult = await db.collection('sh_user_collection')
				.where({user_id: userId})
				.orderBy('sort_order', 'asc')
				.orderBy('create_time', 'desc')
				.get();
			return {
				errCode: 0,
				errMsg: '获取成功',
				data: collectionResult.data
			}
		} catch (error) {
			console.error('获取收藏集列表失败:', error);
			return {
				errCode: 'GET_COLLECTION_LIST_FAILED',
				errMsg: '获取收藏集列表失败'
			}
		}
	},

	/**
	 * 创建收藏集
	 * @param {string} collectionName 收藏集名称
	 * @param {string} description 描述
	 * @param {string} coverImage 封面图片
	 * @returns {object} 创建结果
	 */
	async createCollection({collectionName, description, coverImage}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		if (!collectionName) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '用户ID和收藏集名称不能为空'
			}
		}
		const userId = uid

		try {
			const db = uniCloud.database();
			
			// 检查收藏集名称是否重复
			const existCollection = await db.collection('sh_user_collection').where({
				user_id: userId,
				collection_name: collectionName
			}).get();

			if (existCollection.data.length > 0) {
				return {
					errCode: 'COLLECTION_EXISTS',
					errMsg: '收藏集名称已存在'
				}
			}

			// 获取当前收藏集数量作为排序依据
			const countResult = await db.collection('sh_user_collection').where({
				user_id: userId
			}).count();

			// 创建收藏集
			const collectionResult = await db.collection('sh_user_collection').add({
				user_id: userId,
				collection_name: collectionName,
				description: description || '',
				cover_image: coverImage || '',
				pattern_count: 0,
				is_default: false,
				sort_order: countResult.total,
				create_time: new Date(),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '创建成功',
				data: {
					collectionId: collectionResult.id
				}
			}
		} catch (error) {
			console.error('创建收藏集失败:', error);
			return {
				errCode: 'CREATE_COLLECTION_FAILED',
				errMsg: '创建收藏集失败'
			}
		}
	},

	/**
	 * 更新收藏集信息
	 * @param {string} collectionId 收藏集ID
	 * @param {object} collectionInfo 收藏集信息
	 * @returns {object} 更新结果
	 */
	async updateCollection({collectionId, collectionInfo}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)

		if (!collectionId || !userId || !collectionInfo) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查权限
			const collectionResult = await db.collection('sh_user_collection').where({
				_id: collectionId,
				user_id: userId
			}).get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			// 过滤允许更新的字段
			const allowedFields = ['collection_name', 'description', 'cover_image'];
			const updateData = {};
			
			allowedFields.forEach(field => {
				if (collectionInfo[field] !== undefined) {
					updateData[field] = collectionInfo[field];
				}
			});
			
			updateData.update_time = new Date();

			// 如果更新名称，检查是否重复
			if (updateData.collection_name) {
				const existCollection = await db.collection('sh_user_collection').where({
					user_id: userId,
					collection_name: updateData.collection_name,
					_id: db.command.neq(collectionId)
				}).get();

				if (existCollection.data.length > 0) {
					return {
						errCode: 'COLLECTION_NAME_EXISTS',
						errMsg: '收藏集名称已存在'
					}
				}
			}

			await db.collection('sh_user_collection').doc(collectionId).update(updateData);

			return {
				errCode: 0,
				errMsg: '更新成功'
			}
		} catch (error) {
			console.error('更新收藏集失败:', error);
			return {
				errCode: 'UPDATE_COLLECTION_FAILED',
				errMsg: '更新收藏集失败'
			}
		}
	},

	/**
	 * 删除收藏集
	 * @param {string} collectionId 收藏集ID
	 * @returns {object} 删除结果
	 */
	async deleteCollection({collectionId}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)

		if (!collectionId || !userId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查权限
			const collectionResult = await db.collection('sh_user_collection').where({
				_id: collectionId,
				user_id: userId
			}).get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0];
			
			// 不能删除默认收藏集
			if (collection.is_default) {
				return {
					errCode: 'CANNOT_DELETE_DEFAULT',
					errMsg: '不能删除默认收藏集'
				}
			}

			// 将该收藏集中的收藏移动到默认收藏集
			await db.collection('sh_user_favorite').where({
				user_id: userId,
				collection_id: collectionId
			}).update({
				collection_id: null
			});

			// 删除收藏集
			await db.collection('sh_user_collection').doc(collectionId).remove();

			return {
				errCode: 0,
				errMsg: '删除成功'
			}
		} catch (error) {
			console.error('删除收藏集失败:', error);
			return {
				errCode: 'DELETE_COLLECTION_FAILED',
				errMsg: '删除收藏集失败'
			}
		}
	},

	/**
	 * 获取收藏集详情和图案列表
	 * @param {string} collectionId 收藏集ID
	 * @param {number} page 页码
	 * @param {number} limit 每页数量
	 * @returns {object} 收藏集详情
	 */


	/**
	 * 移动图案到不同收藏集
	 * @param {string} userId 用户ID
	 * @param {string} patternId 图案ID
	 * @param {string} fromCollectionId 源收藏集ID
	 * @param {string} toCollectionId 目标收藏集ID
	 * @returns {object} 移动结果
	 */
	async movePattern({userId, patternId, fromCollectionId, toCollectionId}) {
		if (!userId || !patternId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查收藏记录是否存在
			let whereCondition = {
				user_id: userId,
				pattern_id: patternId
			};
			
			if (fromCollectionId) {
				whereCondition.collection_id = fromCollectionId;
			} else {
				whereCondition.collection_id = dbCmd.or([null, '']);
			}
			
			const favoriteResult = await db.collection('sh_user_favorite')
				.where(whereCondition)
				.get();

			if (favoriteResult.data.length === 0) {
				return {
					errCode: 'FAVORITE_NOT_FOUND',
					errMsg: '收藏记录不存在'
				}
			}

			// 如果目标收藏集存在，检查权限
			if (toCollectionId) {
				const collectionResult = await db.collection('sh_user_collection').where({
					_id: toCollectionId,
					user_id: userId
				}).get();

				if (collectionResult.data.length === 0) {
					return {
						errCode: 'TARGET_COLLECTION_NOT_FOUND',
						errMsg: '目标收藏集不存在'
					}
				}
			}

			// 检查目标收藏集中是否已存在该图案
			let targetWhereCondition = {
				user_id: userId,
				pattern_id: patternId
			};
			
			if (toCollectionId) {
				targetWhereCondition.collection_id = toCollectionId;
			} else {
				targetWhereCondition.collection_id = dbCmd.or([null, '']);
			}
			
			const existResult = await db.collection('sh_user_favorite')
				.where(targetWhereCondition)
				.get();

			if (existResult.data.length > 0) {
				return {
					errCode: 'PATTERN_EXISTS_IN_TARGET',
					errMsg: '图案已在目标收藏集中'
				}
			}

			// 更新收藏记录
			await db.collection('sh_user_favorite').doc(favoriteResult.data[0]._id).update({
				collection_id: toCollectionId || null
			});

			return {
				errCode: 0,
				errMsg: '移动成功'
			}
		} catch (error) {
			console.error('移动图案失败:', error);
			return {
				errCode: 'MOVE_PATTERN_FAILED',
				errMsg: '移动图案失败'
			}
		}
	},

	/**
	 * 调整收藏集排序
	 * @param {string} userId 用户ID
	 * @param {array} collections 收藏集排序列表
	 * @returns {object} 调整结果
	 */
	async reorderCollections({userId, collections}) {
		if (!userId || !Array.isArray(collections)) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空或格式错误'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 批量更新排序
			const updatePromises = collections.map((collection, index) => {
				return db.collection('sh_user_collection').where({
					_id: collection.id,
					user_id: userId
				}).update({
					sort_order: index,
					update_time: new Date()
				});
			});

			await Promise.all(updatePromises);

			return {
				errCode: 0,
				errMsg: '调整排序成功'
			}
		} catch (error) {
			console.error('调整收藏集排序失败:', error);
			return {
				errCode: 'REORDER_COLLECTIONS_FAILED',
				errMsg: '调整收藏集排序失败'
			}
		}
	},

	/**
	 * 获取用户收藏集（用于前端调用）
	 * @param {object} params 查询参数
	 * @returns {object} 收藏集列表
	 */
	async getUserCollections(params = {}) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			if (code !== 0 || !uid) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}
			const userId = uid

			const db = uniCloud.database();
			
			// 构建查询条件
			const where = { user_id: userId };
			
			// 分页参数
			const pageIndex = params.pageIndex || 1;
			const pageSize = params.pageSize || 20;
			const skip = (pageIndex - 1) * pageSize;

			// 查询收藏集列表
			const collectionResult = await db.collection('sh_user_collection')
				.where(where)
				.orderBy('sort_order', 'asc')
				.orderBy('create_time', 'desc')
				.skip(skip)
				.limit(pageSize)
				.get();

			// 统计每个收藏集的图案数量
			const collections = [];
			for (const collection of collectionResult.data) {
				// 直接从patterns字段计算图案数量
				const patternCount = collection.patterns ? collection.patterns.length : 0;

				collections.push({
					...collection,
					pattern_count: patternCount
				});
			}

			// 获取总数
			const totalResult = await db.collection('sh_user_collection')
				.where(where)
				.count();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					list: collections,
					total: totalResult.total,
					pageIndex,
					pageSize,
					hasMore: totalResult.total > pageIndex * pageSize
				}
			}
		} catch (error) {
			console.error('获取用户收藏集失败:', error);
			return {
				errCode: 'GET_USER_COLLECTIONS_FAILED',
				errMsg: '获取用户收藏集失败'
			}
		}
	},

	/**
	 * 获取收藏集详情（包含图案列表）
	 * @param {string} collectionId 收藏集ID
	 * @returns {object} 收藏集详情
	 */
	async getCollectionDetail({ collectionId }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			const userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!collectionId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '收藏集ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 获取收藏集详情
			const collectionResult = await db.collection('sh_user_collection')
				.where({
					_id: collectionId,
					user_id: userId
				})
				.get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0];
			
			// 如果patterns字段存在且包含图案，获取完整的图案信息
			let patterns = [];
			if (collection.patterns && collection.patterns.length > 0) {
				// 查询图案详细信息
				const patternIds = collection.patterns.map(p => p.pattern_id);
				
				const patternResult = await db.collection('sh_pattern')
					.where({
						_id: db.command.in(patternIds)
					})
					.get();
				
				// 合并图案信息和收藏时间，按排序顺序排列
				patterns = collection.patterns.map(collectionPattern => {
					const patternInfo = patternResult.data.find(p => p._id === collectionPattern.pattern_id);
					return {
						id: collectionPattern.pattern_id,
						name: patternInfo?.pattern_name || '未知图案',
						cover: patternInfo?.preview_image || '',
						category: patternInfo?.category || '',
						tags: patternInfo?.tags || [],
						sort_order: collectionPattern.sort_order || 0,
						update_time: collectionPattern.update_time
					};
				})
				.sort((a, b) => a.sort_order - b.sort_order); // 按排序顺序排列

			}

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					...collection,
					patterns: patterns
				}
			}
		} catch (error) {
			console.error('获取收藏集详情失败:', error);
			return {
				errCode: 'GET_COLLECTION_DETAIL_FAILED',
				errMsg: '获取收藏集详情失败'
			}
		}
	},

	/**
	 * 创建收藏集（用于前端调用）
	 * @param {object} data 收藏集数据
	 * @returns {object} 创建结果
	 */
	async createCollection(data) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			const userId = uid
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!data.name || !data.name.trim()) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '收藏集名称不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查收藏集名称是否重复
			const existResult = await db.collection('sh_user_collection')
				.where({
					user_id: userId,
					name: data.name.trim()
				})
				.get();

			if (existResult.data.length > 0) {
				return {
					errCode: 'COLLECTION_EXISTS',
					errMsg: '收藏集名称已存在'
				}
			}

			// 创建收藏集
			const collectionData = {
				user_id: userId,
				name: data.name.trim(),
				description: data.description || '',
				cover_image: data.cover_image || '',
				patterns: [], // 新增：图案列表字段
				is_public: data.is_public || false,
				sort_order: data.sort_order || 0,
				create_time: new Date(),
				update_time: new Date()
			};

			const result = await db.collection('sh_user_collection').add(collectionData);

			if (result.id) {
				return {
					errCode: 0,
					errMsg: '创建成功',
					data: {
						_id: result.id,
						...collectionData
					}
				}
			} else {
				return {
					errCode: 'CREATE_COLLECTION_FAILED1',
					errMsg: '创建收藏集失败'
				}
			}
		} catch (error) {
			console.error('创建收藏集失败:', error);
			return {
				errCode: 'CREATE_COLLECTION_FAILED2',
				errMsg: '创建收藏集失败'
			}
		}
	},

	/**
	 * 删除收藏集
	 * @param {string} collectionId 收藏集ID
	 * @returns {object} 删除结果
	 */
	async deleteCollection({ collectionId }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			const userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!collectionId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '收藏集ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查收藏集是否存在且属于当前用户
			const collectionResult = await db.collection('sh_user_collection')
				.where({
					_id: collectionId,
					user_id: userId
				})
				.get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			// 删除收藏集中的所有收藏项
			await db.collection('sh_user_favorite')
				.where({
					user_id: userId,
					collection_id: collectionId
				})
				.remove();

			// 删除收藏集
			const deleteResult = await db.collection('sh_user_collection')
				.doc(collectionId)
				.remove();

			if (deleteResult.deleted === 1) {
				return {
					errCode: 0,
					errMsg: '删除成功'
				}
			} else {
				return {
					errCode: 'DELETE_COLLECTION_FAILED',
					errMsg: '删除收藏集失败'
				}
			}
		} catch (error) {
			console.error('删除收藏集失败:', error);
			return {
				errCode: 'DELETE_COLLECTION_FAILED',
				errMsg: '删除收藏集失败'
			}
		}
	},

	/**
	 * 添加图案到收藏集
	 * @param {string} collectionId 收藏集ID
	 * @param {string} patternId 图案ID
	 * @returns {object} 添加结果
	 */
	async addPatternToCollection({ collectionId, patternId }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			const userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!collectionId || !patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '收藏集ID和图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查收藏集是否存在且属于当前用户
			const collectionResult = await db.collection('sh_user_collection')
				.where({
					_id: collectionId,
					user_id: userId
				})
				.get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			// 检查图案是否存在
			const patternResult = await db.collection('sh_pattern').doc(patternId).get();
			if (patternResult.data.length === 0) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不存在'
				}
			}

			const collection = collectionResult.data[0];
			
			// 检查是否已在该收藏集中（检查patterns数组）
			const patterns = collection.patterns || [];
			const existingPattern = patterns.find(p => p.pattern_id === patternId);
			
			if (existingPattern) {
				return {
					errCode: 'PATTERN_EXISTS',
					errMsg: '图案已在该收藏集中'
				}
			}

			// 检查是否已在收藏表中存在
			const existResult = await db.collection('sh_user_favorite')
				.where({
					user_id: userId,
					pattern_id: patternId,
					collection_id: collectionId
				})
				.get();

			// 添加到收藏表
			if (existResult.data.length === 0) {
				const favoriteData = {
					user_id: userId,
					pattern_id: patternId,
					collection_id: collectionId,
					create_time: new Date()
				};
				await db.collection('sh_user_favorite').add(favoriteData);
			}

			// 更新收藏集的patterns字段
			const maxSortOrder = patterns.length > 0 ? Math.max(...patterns.map(p => p.sort_order || 0)) : 0;
			
			const newPattern = {
				pattern_id: patternId,
				sort_order: maxSortOrder + 1,
				add_time: new Date()
			};
			
			await db.collection('sh_user_collection').doc(collectionId).update({
				patterns: db.command.push(newPattern),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '添加成功'
			}
		} catch (error) {
			console.error('添加图案到收藏集失败:', error);
			return {
				errCode: 'ADD_PATTERN_TO_COLLECTION_FAILED',
				errMsg: '添加图案到收藏集失败'
			}
		}
	},

	/**
	 * 从收藏集移除图案
	 * @param {string} collectionId 收藏集ID
	 * @param {string} patternId 图案ID
	 * @returns {object} 移除结果
	 */
	async removePatternFromCollection({ collectionId, patternId }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			const userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!collectionId || !patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '收藏集ID和图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查收藏集是否存在且属于当前用户
			const collectionResult = await db.collection('sh_user_collection')
				.where({
					_id: collectionId,
					user_id: userId
				})
				.get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0];
			
			// 检查图案是否在该收藏集中（检查patterns数组）
			const patterns = collection.patterns || [];
			const patternIndex = patterns.findIndex(p => p.pattern_id === patternId);
			
			if (patternIndex === -1) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不在该收藏集中'
				}
			}

			// 从收藏表中移除
			await db.collection('sh_user_favorite')
				.where({
					user_id: userId,
					pattern_id: patternId,
					collection_id: collectionId
				})
				.remove();

			// 从收藏集的patterns字段中移除
			const updatedPatterns = patterns.filter(p => p.pattern_id !== patternId);
			
			await db.collection('sh_user_collection').doc(collectionId).update({
				patterns: updatedPatterns,
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '移除成功'
			}
		} catch (error) {
			console.error('从收藏集移除图案失败:', error);
			return {
				errCode: 'REMOVE_PATTERN_FROM_COLLECTION_FAILED',
				errMsg: '从收藏集移除图案失败'
			}
		}
	},

	/**
	 * 重新排序收藏集中的图案
	 * @param {string} collectionId 收藏集ID
	 * @param {array} patternOrders 图案排序数组 [{pattern_id: string, sort_order: number}]
	 * @returns {object} 排序结果
	 */
	async reorderPatternsInCollection({ collectionId, patternOrders }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			const userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!collectionId || !Array.isArray(patternOrders)) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '收藏集ID和图案排序数组不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查收藏集是否存在且属于当前用户
			const collectionResult = await db.collection('sh_user_collection')
				.where({
					_id: collectionId,
					user_id: userId
				})
				.get();

			if (collectionResult.data.length === 0) {
				return {
					errCode: 'COLLECTION_NOT_FOUND',
					errMsg: '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0];
			const patterns = collection.patterns || [];
			
			// 更新图案的排序顺序
			const updatedPatterns = patterns.map(pattern => {
				const orderInfo = patternOrders.find(order => order.pattern_id === pattern.pattern_id);
				if (orderInfo) {
					return {
						...pattern,
						sort_order: orderInfo.sort_order
					};
				}
				return pattern;
			});
			
			await db.collection('sh_user_collection').doc(collectionId).update({
				patterns: updatedPatterns,
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '排序成功'
			}
		} catch (error) {
			console.error('重新排序收藏集图案失败:', error);
			return {
				errCode: 'REORDER_PATTERNS_FAILED',
				errMsg: '重新排序收藏集图案失败'
			}
		}
	}
}
